<template>
  <div>
    <!-- 下拉加载刷新 -->
    <van-pull-refresh
      v-model="isLoading"
      @refresh="onRefresh"
      :disabled="finished"
    >
      <!-- 上拉加载更多 -->
      <!--
      immediate-check:false 防止一进来就触发load事件
     -->
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :immediate-check="false"
      >
        <Artitem
          v-for="item in artlist"
          :key="item.art_id"
          :article="item"
          @remove-article="removeArtcile"
        ></Artitem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArtListAPI } from '../../api/homeApi'
import Artitem from '../Artitem/Artitem.vue'
export default {
  name: 'Artlist',
  // 为文章列表组件,封装名为channelId的props
  props: {
    channelId: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      // 文章列表的数据
      artlist: [],
      // 调用API
      // 接口要传递的时间戳
      timestamp: Date.now(),
      // 是否正在加载数据
      loading: true,
      // 所有数据是否加载完毕
      finished: false,
      // 是否正在请求下拉刷新的数据
      isLoading: false
    }
  },
  created () {
    this.initArtList()
  },
  methods: {
    // isPullDown是一个布尔值,如果为true,表示用户执行的下拉刷新的动作
    async initArtList (isPullDown) {
      const { data: res } = await getArtListAPI(this.channelId, this.timestamp)
      console.log(res)
      if (res.message === 'OK') {
        this.timestamp = res.data.pre_timestamp
        // this.artlist = res.data.results
        //  this.artlist = [...旧数据, ...新数据]
        if (isPullDown) {
          this.artlist = [...res.data.results, ...this.artlist]
        } else {
          this.artlist = [...this.artlist, ...res.data.results]
        }
        this.isLoading = false
        this.loading = false
        // 判断所有数据是否加载完毕了
        if (res.data.pre_timestamp === null) {
          this.finished = true
        }
        if (res.data.pre_timestamp === null) {
          this.finished = true
        }
      }
    },
    // 触发上啦加载更多的load事件
    onLoad () {
      console.log('上拉加载更多')
      // 在load事件中,调用initArtList方法,加载下一页数据
      this.initArtList(false)
    },
    onRefresh () {
      console.log('下拉刷新')
      this.initArtList(true)
    },
    removeArtcile (id) {
      this.artlist = this.artlist.filter(item => item.art_id !== id)
      if (this.artlist.length < 10) {
        // 每次删除一条文章数据之后,立即判断剩下数据条数是否小于10
        // 如果小于10,则自动请求下一页数据,防止页面空白,导致上啦加载更多不生效的问题
        this.initArtList()
      }
    }

  },
  components: {
    Artitem
  }
}
</script>

<style lang="less" scoped>
</style>
